package cc.eddic.practice.concurrency.impl;

import cc.eddic.practice.concurrency.LogItem;
import cc.eddic.practice.concurrency.LogItemParser;
import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class LogItemParseLxImpl implements LogItemParser {
//    解析每一个log文件的内容
    @Override
    public Optional<LogItem> parse(String line) {

        val m = pattern.matcher(line);
        if (!m.matches()) {
            log.error("Error parsing line: {}", line);
            return Optional.empty();
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH);
        LocalDateTime localDateTime = LocalDateTime.parse(m.group("dt"), formatter);
        String request=m.group("request");
        Matcher matcher=REQUEST_PATTERN.matcher(request);
        if(matcher.matches()){
            String method=matcher.group("method");
            String url=matcher.group("url");
            String protocol=matcher.group("protocol");
            String path;
            if(url.contains("?")){
                int index=url.indexOf('?');
                path=url.substring(0,index);
            }else{
                path=url;
            }
            return Optional.of(new LogItem(m.group("ip"),localDateTime,m.group("request"),method,path,new HashMap<>(),
                    protocol,Integer.parseInt(m.group("status")),Long.parseLong(m.group("sent")),
                    m.group("referer"),m.group("ua")));
        }else{
            return Optional.of(new LogItem(m.group("ip"),localDateTime,m.group("request"),null,null,new HashMap<>(),
                    null,Integer.parseInt(m.group("status")),Long.parseLong(m.group("sent")),
                    m.group("referer"),m.group("ua")));
        }
    }
    private static final Pattern pattern = Pattern.compile("(?<ip>\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+[\\w\\-]+\\s+[\\w\\-]+\\s+\\[(?<dt>\\d+/\\w+/\\d+:\\d+:\\d+:\\d+\\s+\\+\\d+)]\\s+\"(?<request>.*)\"\\s+(?<status>\\d+)\\s+(?<sent>\\d+)\\s+\"(?<referer>[^\"]+)\"\\s+\"(?<ua>[^\"]+)\"");
    private static final Pattern REQUEST_PATTERN = Pattern.compile("(?<method>\\w+)\\s+(?<url>[^ ]+)\\s+(?<protocol>[^ ]+)");

}

